import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther zzyy
 * @create 2024-08-02 20:36
 */
public class SyncVSLockDemo {

    /**
     * 没有退出机制
     */
    public synchronized void m1() {
//暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "\t" + "---come in");
    }

    private Lock lock = new ReentrantLock();

    public void m2() {
        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName() + "\t" + "----come in");
//暂停几秒钟线程
                try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}

            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "\t" + "----抢锁失败，请重试");
        }
    }

    public void m3() {
        try {
            if (lock.tryLock(2, TimeUnit.SECONDS)) {
                try {
                    System.out.println(Thread.currentThread().getName() + "\t" + "----come in");
                    try {
                        TimeUnit.SECONDS.sleep(4);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "\t" + "----持续2秒，抢锁失败，请重试");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        SyncVSLockDemo syncVSLockDemo = new SyncVSLockDemo();

        new Thread(() -> {
            syncVSLockDemo.m2();
        }, "t1").start();

        new Thread(() -> {
            syncVSLockDemo.m2();
        }, "t2").start();
    }
}


